<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="98px">
      <el-form-item label="当事人名称" prop="partyName">
        <el-input
          v-model="queryParams.partyName"
          placeholder="请输入当事人名称"
          clearable
          :style="{
            width: '18vw',
          }"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="立案号" prop="caseId">
        <el-input
          v-model="queryParams.caseId"
          placeholder="请输入立案号"
          clearable
          :style="{
            width: '18vw',
          }"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="行政处罚决定书文号" prop="decisionsNo" class="long-label">
        <el-input
          v-model="queryParams.decisionsNo"
          placeholder="请输入行政处罚决定书文号"
          clearable
          :style="{
            width: '18vw',
          }"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="登记时间">
        <el-date-picker
          v-model="daterangeCreateTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :style="{
            width: '18vw',
          }"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb10">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['penaltydecisions:penaltydecisions:add']">
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['penaltydecisions:penaltydecisions:edit']">
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['penaltydecisions:penaltydecisions:remove']">
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['penaltydecisions:penaltydecisions:export']">
          导出送达回证
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['penaltydecisions:penaltydecisions:export']">
          导出处罚决定书
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="penaltydecisionsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="文书名称" align="center" prop="name" />
      <el-table-column label="行政处罚决定书文号" align="center" prop="decisionsNo" />
      <el-table-column label="立案号" align="center" prop="caseId" />
      <el-table-column label="当事人名称" align="center" prop="partyName" />
      <el-table-column label="登记时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['penaltydecisions:penaltydecisions:edit']">
            修改
          </el-button>
          <el-button link type="primary" icon="view" @click="handlePreview(scope.row)">预览</el-button>
          <el-button link type="primary" icon="upload" @click="handleUpload(scope.row)">上传附件</el-button>
          <el-button
            link
            type="danger"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['penaltydecisions:penaltydecisions:remove']">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改处罚决定书对话框 -->
    <el-dialog :title="title" v-model="open" width="1200px" append-to-body>
      <el-form ref="penaltydecisionsRef" :model="form" :rules="rules" label-width="138px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="立案号" prop="caseId">
              <el-select v-model="form.caseId" placeholder="请选择立案号" clearable @change="handleCase">
                <el-option v-for="item in numberList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="当事人名称" prop="partyName">
              <el-input v-model="form.partyName" disabled placeholder="请输入当事人名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="法定代表人" prop="legalRepresentative">
              <el-input v-model="form.legalRepresentative" disabled placeholder="请输入法定代表人" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="营业执照类型" prop="businessType">
              <el-input v-model="form.businessType" disabled placeholder="请输入营业执照类型" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="统一社会信用代码" prop="creditCode">
              <el-input v-model="form.creditCode" disabled placeholder="请输入统一社会信用代码" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="地址" :rules="rules.addressObj" prop="addressObj">
              <locationSelect v-model="form.addressObj" disabled style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="案情说明" prop="caseDesc">
              <div class="inline-edit-container">
                <!-- 使用contenteditable的div作为大输入框 -->
                <div
                  ref="caseDescAdminis"
                  class="editable-text-area"
                  contenteditable="true"
                  @blur="handleTextChange"
                  @keydown="e => handleKeyDown(e, caseDescAdminis)">
                  <!-- 文本内容和小输入框混合显示 -->
                  <template v-if="caseDescType === 'withInputs'">
                    <span class="text-content">
                      <span>{{ form.checkDesc }}</span>
                      <span v-html="form.content1"></span>
                    </span>
                    <input
                      v-model="form.caseDesc1"
                      type="number"
                      placeholder="年"
                      class="protected-input"
                      @input="updateInlineInput(1)" />
                    <span class="text-content">年</span>
                    <input
                      v-model="form.caseDesc2"
                      type="number"
                      placeholder="月"
                      class="protected-input"
                      @input="updateInlineInput(2)" />
                    <span class="text-content">月</span>
                    <input
                      v-model="form.caseDesc3"
                      type="number"
                      placeholder="日"
                      class="protected-input"
                      @input="updateInlineInput(3)" />
                    <span class="text-content">日</span>
                    <span v-html="form.content2" class="text-content"></span>
                  </template>
                  <template v-else-if="caseDescType === 'plainText'">
                    <span>{{ form.checkDesc }}</span>
                    {{ form.caseDesc }}
                  </template>
                </div>
                <!-- 隐藏的textarea用于表单验证和数据绑定 -->
                <textarea v-model="form.caseDesc" style="display: none" ref="hiddenTextarea"></textarea>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="证据证明" prop="evidenceDesc">
              <el-input v-model="form.evidenceDesc" :rows="4" type="textarea" placeholder="请输入证据证明" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="违反条例" prop="violationRegulations">
              <el-input v-model="form.violationRegulations" :rows="4" type="textarea" placeholder="请输入违反条例" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="陈述申辩" prop="statementDefense">
              <div class="inline-edit-container">
                <!-- 使用contenteditable的div作为大输入框 -->
                <div
                  ref="statementDefenseRef"
                  class="editable-text-area"
                  contenteditable="true"
                  @blur="handleTextChange2"
                  @keydown="e => handleKeyDown(e, statementDefenseRef)">
                  <!-- 文本内容和小输入框混合显示 -->
                  <span v-html="form.statementDefense1" class="text-content"></span>
                  <span v-if="statementDefenseType === 'withInputs'" class="protected-input-group">
                    <input
                      v-model="form.statementDefense2"
                      type="number"
                      placeholder="年"
                      class="protected-input"
                      @input="updateStatementInput(1)" />
                    <span class="text-content">年</span>
                    <input
                      v-model="form.statementDefense3"
                      type="number"
                      placeholder="月"
                      class="protected-input"
                      @input="updateStatementInput(2)" />
                    <span class="text-content">月</span>
                    <input
                      v-model="form.statementDefense4"
                      type="number"
                      placeholder="日"
                      class="protected-input"
                      @input="updateStatementInput(3)" />
                    <span class="text-content">日</span>
                  </span>
                  <span v-else-if="statementDefenseType === 'plainText'">
                    {{ form.statementDefense }}
                  </span>
                  <span v-html="form.statementDefense5" class="text-content"></span>
                </div>
                <!-- 隐藏的textarea用于表单验证和数据绑定 -->
                <textarea v-model="form.statementDefense" style="display: none" ref="hiddenTextarea"></textarea>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="处理依据" prop="handlingBasis">
              <el-input v-model="form.handlingBasis" :rows="4" type="textarea" placeholder="请输入陈述申辩" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="缴纳罚款告知" prop="paymentNotice">
              <el-input v-model="form.paymentNotice" :rows="4" type="textarea" placeholder="请输入缴纳罚款告知" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="行政复议/诉讼告知" prop="litigationNotice">
              <el-input
                v-model="form.litigationNotice"
                :rows="4"
                type="textarea"
                placeholder="请输入行政复议/诉讼告知" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 上传附件弹窗 -->
    <el-dialog title="上传附件" v-model="fileModal" width="1200px">
      <FileList v-if="fileModal" :fileUploadList="fileUploadList" />
      <template #footer>
        <div class="form-footer">
          <el-button type="primary" @click="handleUploadConfirm">保存</el-button>
          <el-button @click="() => (fileModal = false)">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Penaltydecisions">
import {
  listPenaltydecisions,
  getPenaltydecisions,
  delPenaltydecisions,
  addPenaltydecisions,
  updatePenaltydecisions,
  previewPenaltydecisions,
  addPenaltydecisionsFiles,
  getCaseList,
} from '@/api/caseHandling/administrativePenalty'
import { registrationcaseDetail, penaltydecisionsGetContent } from '@/api/filingReview/register'
import locationSelect from '@/components/locationSelect/index.vue'
import FileList from '@/components/FileList/index.vue'
import { ElMessage } from 'element-plus'
import useCompleteContent from '@/hooks/completeContent.js'

const { proxy } = getCurrentInstance()

const penaltydecisionsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
const daterangeCreateTime = ref([])
// 自定义校验器：检查拍摄地点是否完整
const validateLocation = (rule, value, callback) => {
  if (!value || !value.streetOfPhotoLocation || !value.photoLocation) {
    callback(new Error('请选择拍摄地点'))
  } else {
    callback()
  }
}
const data = reactive({
  form: {
    caseDesc: undefined,
    checkDesc: undefined,
    caseDesc1: undefined,
    caseDesc2: undefined,
    caseDesc3: undefined,
    content1: undefined,
    content2: undefined,
    evidenceDesc: undefined,
    violationRegulations: undefined,
    statementDefense: undefined,
    statementDefense1: undefined,
    statementDefense2: undefined,
    statementDefense3: undefined,
    statementDefense4: undefined,
    statementDefense5: undefined,
    handlingBasis: undefined,
    paymentNotice: undefined,
    litigationNotice: undefined,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    caseId: undefined,
    partyName: undefined,
    partyId: undefined,
    createTime: undefined,
    businessType: undefined,
    creditCode: undefined,
    legalRepresentative: undefined,
  },
  rules: {
    caseId: [{ required: true, message: '立案号不能为空', trigger: ['blur', 'change'] }],
    createTime: [{ required: true, message: '立案时间不能为空', trigger: ['blur', 'change'] }],
    partyName: [{ required: true, message: '当事人名称不能为空', trigger: ['blur', 'change'] }],
    addressObj: [{ required: true, validator: validateLocation, trigger: ['blur', 'change'] }],
    businessType: [{ required: true, message: '营业执照类型不能为空', trigger: 'change' }],
    creditCode: [{ required: true, message: '统一社会信用代码不能为空', trigger: ['blur', 'change'] }],
    legalRepresentative: [{ required: true, message: '法定代表人不能为空', trigger: ['blur', 'change'] }],
    caseDesc: [{ required: true, message: '请输入案情说明', trigger: ['blur', 'change'] }],
    evidenceDesc: [{ required: true, message: '请输入证据证明', trigger: ['blur', 'change'] }],
    violationRegulations: [{ required: true, message: '请输入违反条例', trigger: ['blur', 'change'] }],
    statementDefense: [{ required: true, message: '请输入陈述申辩', trigger: ['blur', 'change'] }],
    handlingBasis: [{ required: true, message: '请输入处理依据', trigger: ['blur', 'change'] }],
    paymentNotice: [{ required: true, message: '请输入缴纳罚款告知', trigger: ['blur', 'change'] }],
    litigationNotice: [{ required: true, message: '请输入行政复议/诉讼告知', trigger: ['blur', 'change'] }],
  },
})

const { queryParams, form, rules } = toRefs(data)
const caseDescType = ref('plainText')
const statementDefenseType = ref('plainText')

/** 查询处罚决定书列表 */
function getList() {
  loading.value = true
  queryParams.value.params = {}
  if (null != daterangeCreateTime && '' != daterangeCreateTime) {
    queryParams.value.params['beginCreateTime'] = daterangeCreateTime.value[0]
    queryParams.value.params['endCreateTime'] = daterangeCreateTime.value[1]
  }
  listPenaltydecisions(queryParams.value).then(response => {
    penaltydecisionsList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    caseId: undefined,
    createTime: undefined,
    partyName: undefined,
    partyId: undefined,
    createTime: undefined,
    businessType: undefined,
    creditCode: undefined,
    legalRepresentative: undefined,
    caseDesc: undefined,
    checkDesc: undefined,
    caseDesc1: undefined,
    caseDesc2: undefined,
    caseDesc3: undefined,
    content1: undefined,
    content2: undefined,
    evidenceDesc: undefined,
    violationRegulations: undefined,
    statementDefense: undefined,
    statementDefense1: undefined,
    statementDefense2: undefined,
    statementDefense3: undefined,
    statementDefense4: undefined,
    statementDefense5: undefined,
    handlingBasis: undefined,
    paymentNotice: undefined,
    litigationNotice: undefined,
  }
  proxy.resetForm('penaltydecisionsRef')
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCreateTime.value = []
  proxy.resetForm('queryRef')
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}
const numberList = ref([])
const handleCaseList = async () => {
  const res = await getCaseList()
  numberList.value = res.data.map(item => ({
    label: item.caseNo,
    value: item.id,
  }))
}
const handleCase = async val => {
  return new Promise(async (resolve, reject) => {
    if (!val) {
      form.value.partyName = ''
      form.value.partyId = ''
      form.value.legalRepresentative = ''
      form.value.businessType = ''
      form.value.creditCode = ''
      form.value.addressObj = {
        photoLocation: '',
        streetOfPhotoLocation: '',
      }
      return
    }
    const res = await registrationcaseDetail(val)
    const {
      partyName,
      partyId,
      legalRepresentative,
      businessType,
      unifiedSocialCreditCode,
      streetOfCompanyAddress,
      address,
    } = res.data
    form.value.partyName = partyName
    form.value.partyId = partyId
    form.value.legalRepresentative = legalRepresentative
    form.value.businessType = businessType
    form.value.creditCode = unifiedSocialCreditCode
    form.value.addressObj = {
      photoLocation: address,
      streetOfPhotoLocation: streetOfCompanyAddress,
    }
    const res2 = await penaltydecisionsGetContent(val)
    form.value.checkDesc = res2.data.checkDesc
    resolve()
  })
}
/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = '添加处罚决定书'
  form.value.caseDesc = '我局于2021年01月01日对你单位上述行为进行立案调查。'
  parseCaseDescNumbers('我局于2021年01月01日对你单位上述行为进行立案调查。', 'caseDesc1', 'caseDesc2', 'caseDesc3')
  const datePattern = /(\d{4})年?(\d{1,2})月?(\d{1,2})日?/
  const match1 = form.value.caseDesc.match(datePattern)
  if (match1) {
    const matchStart = match1?.index || undefined
    const matchEnd = matchStart + match1[0]?.length || undefined
    form.value.content1 = form.value.caseDesc.slice(0, matchStart)
    form.value.content2 = form.value.caseDesc.slice(matchEnd)
    caseDescType.value = 'withInputs'
  }
  form.value.statementDefense =
    '我局于2025年1月2日以《行政处罚事先告知书》（兴环保监罚告字〔2025〕第XX号）告知该单位陈述申辩权，有《送达回证》为凭。该单位在法定期限内，未提出陈述申辩。'
  parseCaseDescNumbers(
    '我局于2025年1月2日以《行政处罚事先告知书》（兴环保监罚告字〔2025〕第XX号）告知该单位陈述申辩权，有《送达回证》为凭。该单位在法定期限内，未提出陈述申辩。',
    'statementDefense2',
    'statementDefense3',
    'statementDefense4'
  )
  const match2 = form.value.statementDefense.match(datePattern)
  if (match2) {
    const matchStart = match2?.index || undefined
    const matchEnd = matchStart + match2[0]?.length || undefined
    form.value.statementDefense1 = form.value.statementDefense.slice(0, matchStart)
    form.value.statementDefense5 = form.value.statementDefense.slice(matchEnd)
    statementDefenseType.value = 'withInputs'
  }
  handleCaseList()
}
// 从caseDesc中解析年月日数字
const parseCaseDescNumbers = (text, year, month, day) => {
  const yearMatch = text.match(/(\d{4})年/) || [undefined, undefined]
  const monthMatch = text.match(/(\d{1,2})月/) || [undefined, undefined]
  const dayMatch = text.match(/(\d{1,2})日/) || [undefined, undefined]

  // 提取并设置到对应字段
  if (yearMatch) {
    form.value[year] = yearMatch[1]
  }

  if (monthMatch) {
    form.value[month] = monthMatch[1]
  }

  if (dayMatch) {
    form.value[day] = dayMatch[1]
  }

  return {
    year: form.value.caseDesc1,
    month: form.value.caseDesc2,
    day: form.value.caseDesc3,
  }
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getPenaltydecisions(_id).then(async response => {
    form.value = response.data
    handleCaseList()
    await handleCase(form.value.caseId)
    nextTick(() => {
      if (form.value.caseDesc.includes(form.value.checkDesc)) {
        form.value.caseDesc = form.value.caseDesc.replace(form.value.checkDesc, '')
      }
      form.value.addressObj = {
        photoLocation: form.value.address,
        streetOfPhotoLocation: form.value.streetOfCompanyAddress,
      }

      // 解析案情说明的日期和内容
      if (form.value.caseDesc) {
        parseCaseDescNumbers(form.value.caseDesc, 'caseDesc1', 'caseDesc2', 'caseDesc3')

        const datePattern = /(\d{4})?年(\d{1,2})?月(\d{1,2})?日/
        const match1 = form.value.caseDesc.match(datePattern)
        if (match1) {
          const matchStart = match1.index
          const matchEnd = matchStart + match1[0].length
          form.value.content1 = form.value.caseDesc.substring(0, matchStart)
          form.value.content2 = form.value.caseDesc.substring(matchEnd)
          caseDescType.value = 'withInputs'
        } else {
          // 如果没有找到日期模式，就是普通文本
          form.value.content1 = undefined
          form.value.content2 = undefined
          caseDescType.value = 'plainText'
        }
      }

      // 解析陈述申辩的日期和内容
      if (form.value.statementDefense) {
        parseCaseDescNumbers(form.value.statementDefense, 'statementDefense2', 'statementDefense3', 'statementDefense4')

        // 查看有没有日期模式，没有或者不完整的话，就当普通文本处理
        const datePattern = /(\d{4})?年(\d{1,2})?月(\d{1,2})?日/
        const match2 = form.value.statementDefense.match(datePattern)

        if (match2) {
          const matchStart = match2.index
          const matchEnd = matchStart + match2[0].length
          form.value.statementDefense1 = form.value.statementDefense.substring(0, matchStart)
          form.value.statementDefense5 = form.value.statementDefense.substring(matchEnd)
          statementDefenseType.value = 'withInputs'
        } else {
          // 如果没有找到日期模式，就是普通文本
          form.value.statementDefense1 = undefined
          form.value.statementDefense5 = undefined
          statementDefenseType.value = 'plainText'
        }
      }

      open.value = true
      title.value = '修改处罚决定书'
    })
  })
}

// 案情说明 复合框 start =====================================================
const { setCompleteContent } = useCompleteContent()
const caseDescAdminis = ref(null)
// 更新内联输入框时同步更新主文本
const updateInlineInput = type => {
  nextTick(() => {
    if (!form.value.content1 && !form.value.content2) {
      return
    } else {
      form.value.caseDesc = setCompleteContent(caseDescAdminis.value, false)
    }
  })
}

// 处理可编辑div的文本变化
const handleTextChange = val => {
  nextTick(() => {
    form.value.caseDesc = setCompleteContent(caseDescAdminis.value, false)
    const datePattern = /(\d{4})?年(\d{1,2})?月(\d{1,2})?日/
    const match1 = form.value.caseDesc.match(datePattern)
    if ((!form.value.content1 && !form.value.content2) || !match1) {
      form.value.caseDesc = caseDescAdminis.value.innerText.replace(form.value.checkDesc, '')
    }
  })
}
// 案情说明 复合框 end =====================================================

// 陈述申辩 复合框 start =====================================================
const statementDefenseRef = ref(null)
const updateStatementInput = type => {
  nextTick(() => {
    if (!form.value.statementDefense1 && !form.value.statementDefense5) {
      return
    } else {
      form.value.statementDefense = setCompleteContent(statementDefenseRef.value, false)
    }
  })
}

const handleTextChange2 = () => {
  nextTick(() => {
    if (!form.value.statementDefense1 && !form.value.statementDefense5) {
      form.value.statementDefense = statementDefenseRef.value.innerText
    } else {
      form.value.statementDefense = setCompleteContent(statementDefenseRef.value, false)
    }
  })
}
const handleKeyDown = (event, refName) => {
  // // 防止删除保护的输入框
  // const selection = window.getSelection()
  // const range = selection.getRangeAt(0)
  // // 如果是删除键或退格键
  // if (event.key === 'Delete' || event.key === 'Backspace') {
  //   // 检查选中的内容是否包含受保护的输入框
  //   const protectedInputs = refName.querySelectorAll('.protected-input-group')
  //   for (let input of protectedInputs) {
  //     if (range.intersectsNode(input)) {
  //       event.preventDefault()
  //       ElMessage.warning('固定格式不许删除')
  //       return false
  //     }
  //   }
  // }
}
// 陈述申辩 复合框 end =====================================================

// 预览
const previewRow = ref(null)
const handlePreview = async row => {
  previewRow.value = row
  const res = await previewPenaltydecisions(row.id)
  if (!!res.msg) {
    window.open(res.msg)
  } else {
    ElMessage.warning('预览文件不存在')
  }
}
// 上传附件
const fileModal = ref(false)
const fileUploadList = ref([])
const rowId = ref('')
const handleUpload = async row => {
  rowId.value = row.id
  const res = await getPenaltydecisions(row.id)
  fileUploadList.value = res.data.tpenaltyDecisionsFilesList || []
  fileModal.value = true
}
// 上传附件
const handleUploadConfirm = async () => {
  await addPenaltydecisionsFiles({ id: rowId.value, tpenaltyDecisionsFilesList: fileUploadList.value })
  ElMessage.success('保存成功')
  fileModal.value = false
}

/** 提交按钮 */
function submitForm() {
  console.log('form', form.value)
  if (
    !form.value.caseDesc1 ||
    !form.value.caseDesc2 ||
    (!form.value.caseDesc3 && caseDescType.value === 'withInputs')
  ) {
    ElMessage.warning('案情说明中的日期不完整')
    return
  }
  if (
    statementDefenseType.value === 'withInputs' &&
    (!form.value.statementDefense2 || !form.value.statementDefense3 || !form.value.statementDefense4)
  ) {
    ElMessage.warning('陈述申辩中的日期不完整')
    return
  }
  proxy.$refs['penaltydecisionsRef'].validate(valid => {
    if (valid) {
      form.value.address = form.value.addressObj.photoLocation
      form.value.streetOfCompanyAddress = form.value.addressObj.streetOfPhotoLocation
      if (form.value.id != null) {
        updatePenaltydecisions(form.value).then(response => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        addPenaltydecisions(form.value).then(response => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal
    .confirm('是否确定删除处罚决定书编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delPenaltydecisions(_ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    'penaltydecisions/penaltydecisions/export',
    {
      ...queryParams.value,
    },
    `penaltydecisions_${new Date().getTime()}.xlsx`
  )
}

getList()
</script>

<style scoped lang="scss"></style>
